package com.adingxiong.cft.quartz;

import org.quartz.*;
import org.quartz.impl.StdSchedulerFactory;

import java.time.LocalDateTime;

/**
 * @ClassName JobDemo
 * @Description TODO
 * @Author xiongchao
 * @Date 2020/12/7 15:38
 **/
public class JobDemo implements Job {

    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {

        Object tv1 = context.getTrigger().getJobDataMap().get("t1");
        Object tv2 = context.getTrigger().getJobDataMap().get("t2");
        Object jv1 = context.getJobDetail().getJobDataMap().get("j1");
        Object jv2 = context.getJobDetail().getJobDataMap().get("j2");

        Object ojb = null;

        try {
            ojb = context.getScheduler().getContext().get("skey");

        } catch (SchedulerException e) {
            e.printStackTrace();
        }

        System.out.println(String.format("%s: %s",tv1,tv2));
        System.out.println(String.format("%s:%s",jv1,jv2));
        System.out.println(ojb);
        System.out.println(LocalDateTime.now());
    }

    public static void main(String[] args) throws SchedulerException {
        Scheduler scheduler = StdSchedulerFactory.getDefaultScheduler();
        scheduler.getContext().put("skey","svalue");

        //创建一个tigger
        Trigger trigger = TriggerBuilder.newTrigger()
                .withIdentity("trigger1" ,"group1")
                .usingJobData("t1" ,"tv1")
                .withSchedule(SimpleScheduleBuilder.simpleSchedule().withIntervalInSeconds(3).repeatForever())
                .build();

        trigger.getJobDataMap().put("t2","tv2");

        JobDetail jobDetail = JobBuilder.newJob(JobDemo.class)
                .usingJobData("j1","jv1")
                .withIdentity("myjob" ,"mygroup")
                .build();

        jobDetail.getJobDataMap().put("j2","jv2");

        //注册并启动 schedule
        scheduler.scheduleJob(jobDetail,trigger);
        scheduler.start();


    }
}
